<template>
  <div>
    <el-button @click="showDialog(1)" type="primary">新增角色</el-button>
    <br>
    <br>
    <el-table
      :data="tableData"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      :border=true
      :stripe=true >
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="name" label="名称"></el-table-column>
      <el-table-column prop="createTime" sortable label="创建时间"></el-table-column>
      <el-table-column fixed="right" label="操作" width="220">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="block" style="margin-top: 20px;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[15, 50, 100, 200]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalRow">
      </el-pagination>
		</div>

    <el-dialog width="700px" title="新增角色" :visible.sync="dialogFormVisible">
      <el-form :model="form" :label-width="formLabelWidth">
        <el-form-item label="角色名" >
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="权限" >
          <el-tree
            ref="tree"
            :data="data2"
            show-checkbox
            node-key="id"
           
            check-strictly
            :default-checked-keys="form.powerIds"
            :props="defaultProps">
          </el-tree>
        </el-form-item>
        <el-form-item size="large">
          <el-button type="primary" @click="onSubmit">保 存</el-button>
          <el-button @click="dialogFormVisible = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
  import { getRolePage, getPowerList, rolePowers, saveRole, updateRole, deleteRole } from '../../api/apis'
  export default {
    data() {
      return {
        dialogFormVisible: false,
        formLabelWidth: '120px',
        tableData: [],
        loading: true,
        currentPage: 1,
	      pageSize: 15,
        totalRow: 0,
        type: null,
        tableData: [],
        form: {
          id: '',
          name: '',
          powerIds: []
        },
        data2: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      }
    },
    created(){
      this.handleCurrentChange(this.currentPage);
      this.getPowerlist();
    },
    methods: {
      /* 单页pageSize 改变时会触发 */
      handleSizeChange(val) {
				this.pageSize = val;
				this.handleCurrentChange(1);
			},
			handleCurrentChange(val) {
				this.loading = true;
				this.currentPage = val;
				let data = {
					pageNum: val,
					limit: this.pageSize
				}
				getRolePage(data).then((res)=> {
					this.loading = false;
					if(res.status === 200 ){
						if(res.data.code == 0){
              // console.log(res.data)
							this.totalRow = res.data.count;
							this.tableData = res.data.data;
						}else{
							this.$message.error(res.data.msg)
						}
					}
				})
				.catch(function (error) {
					console.log(error);
        });
      },
      /** 权限树列表 */
      getPowerlist(){
        getPowerList().then( (res)=> {
          this.loading = false;
          if(res.status === 200 ){
            if(res.data.code == 0){
              // console.log(res.data.data)
              this.data2 = res.data.data;
            }
          }else{
            this.$message.error(res.data.msg)
          }
        })
        .catch(function(error){
          console.log(error);
        });
      },
      /* 显示新增弹窗 */
      showDialog(val){
        this.type = val;
        this.form = {};
        this.form.powerIds = [];
        this.dialogFormVisible = true;
      },
       /* 保存用户信息 */ 
      onSubmit(){
        this.form.powerIds=this.$refs.tree.getCheckedKeys()
        if(this.type == 1){
          saveRole( this.form ).then((res)=>{
            // console.log(res)
            if(res.status === 200 ){
              if(res.data.code == 0){
                this.$message({
                  type: 'success',
                  message: '角色新增权限成功!'
                });
                this.dialogFormVisible = false;
                this.handleCurrentChange(1);
              }
            }
          })
          .catch(function(error){
            console.log(error)
          })
        }else{
          updateRole( this.form ).then((res)=>{
            // console.log(res)
            if(res.status === 200 ){
              if(res.data.code == 0){
                this.$message({
                  type: 'success',
                  message: '角色修改权限成功!'
                });
                this.dialogFormVisible = false;
                this.handleCurrentChange(this.currentPage);
              }
            }
          })
          .catch(function(error){
            console.log(error)
          })
        }
      },
      /** 编辑角色 */
      handleEdit(index, row) {
        this.type = 2;
        this.form = {
          id: row.id,
          name: row.name,
        }
        this.dialogFormVisible = true;
        rolePowers({id: row.id}).then((res) => {
          if(res.status == 200){
            if(res.data.code == 0){
              // console.log(res.data.data)
              this.$refs.tree.setCheckedKeys(res.data.data);
            }
          }
        })
        .catch(function(error){
          console.log(error)
        })
      },
      /** 删除该角色权限 */
      handleDelete(index, row) {
        this.$confirm('确定要删除该角色权限吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteRole({id: row.id}).then((res)=>{
            if(res.status == 200){
              if(res.data.code == 0){
                this.$message({
                  type: 'success',
                  message: '角色权限删除成功!'
                });
                this.dialogFormVisible = false;
                this.handleCurrentChange(1);
              }
            }
          })
          .catch(function(error){
            console.log(error);
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
      } 
    }
  }
</script>

<style scoped>
  .el-tree{
     
    padding-top: 10px !important;
    padding-bottom: 10px !important;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
  }
</style>
